import 'dart:io';
import 'dart:ui';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:liuxlcommon/lget/lget.dart';
import 'package:liuxlcommon/view/extension_widget.dart';
import 'package:love_newf/app/com/view/webview/my_web/my_web_page.dart';
import 'package:love_newf/generated/l10n.dart';
import 'package:love_newf/value/app_const.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/toast_util.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';
import 'package:love_newf/app/com/base/app.dart';
import 'package:love_newf/generated/assets.dart';
import 'package:love_newf/value/app_colors.dart';
import 'package:love_newf/value/app_lstyle.dart';
import 'package:permission_handler/permission_handler.dart';

class CommonView {
  static loginSafetyVerifyDialog({required Function() confirm}) {
    return commDialog(confirm: confirm, children: [
      // LText("Por favor confirmar",
      //     lStyle: AppLStyle.titleStyle..fontSize = 18.sp),
      LText("Por favor confirmar",
          lStyle: AppLStyle.titleStyle..textAlign = TextAlign.center),
      LSizeH(10.w),
      LText(
          "Para facilitar la finalización de la verificación del dispositivo, leeremos su SMS de verificación para confirmar el estado de envío del SMS de verificación de su dispositivo.",
          lStyle:
              LStyle(textAlign: TextAlign.center, color: AppColors.textColor)),
    ]);
  }

  static loginAgreenDialog({onConfirm, agree = true}) {
    var xy = GetBuilder<CommonControll>(
        init: CommonControll(),
        builder: (logic) => LRow(
              lStyle: LStyle(
                  width: double.infinity,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center),
              children: [
                LSizeBoxWidth(5.w),
                LText.easy("请阅读", 14.sp, FontWeight.w400),
                InkWell(
                    child: Text("《隐私政策》",
                        style: TextStyle(
                            decoration: TextDecoration.underline,
                            color: AppColors.primaryColor,
                            fontSize: 14.sp)),
                    onTap: () async {
                      // HttpRequest.requestDefaultParamsModel =
                      //     await DeviceDataPlugin.getRequestDefaultParams;
                      Get.to(MyWebPage(url: "https://pinv.whhyn.shop/c.html"));
                    }),
                LText.easy("来了解详情信息", 14.sp, FontWeight.w400),
              ],
            ));

    commDialog(
        cancelTxt: "退出",
        confirmTxt: "同意",
        cancel: () {
          exit(0);
        },
        confirm: () {
          onConfirm();

          // if (agree) {
          //   onConfirm();
          // } else {
          //   ToastUtils.toast(
          //       "Por favor, acepte y marque el acuerdo de privacidad");
          // }
        },
        children: [
          WillPopScope(
            onWillPop: () async {
              return Future.value(false);
            },
            child: LColumn(
              lStyle: LStyle(
                  padding: EdgeInsets.symmetric(horizontal: 1.w),
                  height: Get.height / 10 * 3),
              children: [
                [
                  20.lsh,
                  SizedBox(
                      width: double.infinity,
                      child: Stack(children: [
                        LText("隐私政策",
                            lStyle: LStyle(
                                textAlign: TextAlign.center,
                                fontSize: 24.sp,
                                color: const Color(0xFF23262F))),
                      ])),
                  LSizeBoxHeight(14.w),
                  LText(
                      "在您使用过程中，我们可能会获取您设备包含但不限于相机权限、相册权限、位置权限、存储权限等信息。您可以在相关页面访问、修改、删除您的个人信息或管理您的授权。",
                      lStyle: LStyle(
                          fontSize: 14.sp, color: const Color(0xFF777E90))),
                  xy
                ].column,
                LSizeH(10.w),
              ],
            ),
          )
        ]);
  }

  static bottomDialog(
      {String? title,
      String? message,
      required List<Widget> children,
      confirm,
      height,
      confirmTxt}) {
    Get.bottomSheet(
        LColumn.eazy([
          LRow.eazy([
            20.lsw,
            LText.easy(title, 17.w, fw5, Colors.white)
                .align(Alignment.center)
                .size(null, 53.w),
            LExpand(),
            LContainer(
                child:
                    Image.asset(Assets.iconSearch, height: 20.w, width: 77.w),
                onTap: () => Get.back()).margin(bottom: 10.w),
            15.lsw
          ]),
          ...children,
          LExpand(),
          LText(confirmTxt ?? S.current.confirm,
              lStyle: confrimSty..width = 335.w, onTap: confirm),
          LSizeH(LGet.bottomPadding(App.appContext) + 10.w)
        ]).size(375.w, height ?? 399.w).bgImg(Assets.iconSearch),
        isScrollControlled: true);
  }

  static idPanDialog(confirm) {
    return commDialog(confirm: confirm, title: 'CORRECT CASE', children: [
      LText.easy(
              'Please follow the example to take a photo of a face correctly',
              12.sp)
          .textAlign(TextAlign.center),
      // LImage.easy(Assets.bgImgPan, 191.w, 291.w).margin(top: 23.w, bottom: 20.w),
      // LImage.easy(Assets.bgImgPanDialog, 77.w, 299.w).margin(bottom: 34.w),
      LText.easy('Please click to start certification', 16.sp, fw5,
              0xFFF75B00.color)
          .margin(bottom: 29.w),
    ]);
  }

  static signOutDialog() {
    bool agree = false;
    return commDialog(
        title: "注销账号",
        confirm: () {
          if (agree) {
            Get.back();
            App.logout();
          } else {
            ToastUtils.toast('请同意以上内容！');
          }
        },
        children: [
          14.lsh,
          LColumn(
              lStyle: LStyle(
                  backgroundColor: const Color(0xFfF5F5F9),
                  padding: EdgeInsets.all(14.w),
                  margin: EdgeInsets.symmetric(horizontal: 20.w)),
              children: [
                LText.easy("登出后，您的帐户将不再存在。您提交的所有信息将被删除!", 12.sp),
                LText.easy("为确保您的帐号安全，请您在申请前确认帐号相关服务已正确处理，并注意以下规定:", 12.sp,
                    null, AppColors.primaryColor),
              ]),
          24.lsh,
          GetBuilder(
              init: CommonControll(),
              builder: (l) => LRow(
                    lStyle: LStyle(),
                    children: [
                      LImage(
                        agree ? Assets.loginChecked : Assets.loginCheck,
                        lStyle: LStyle(
                            height: 14.w,
                            padding: const EdgeInsets.symmetric(horizontal: 5)),
                        onTap: () {
                          agree = !agree;
                          l.update();
                        },
                      ),
                      LText.easy("本人已阅读并同意以上内容!", 12.sp)
                    ],
                    onTap: () {
                      agree = !agree;
                      l.update();
                    },
                  )),
          24.lsh
        ]);
  }

  static commDialog(
      {required Function() confirm,
      Function()? cancel,
      String? confirmTxt,
      String? cancelTxt,
      message,
      title,
      width,
      height,
      List<Widget>? children,
      marginTop,
      bgWhite,
      bgImg,
      isShowClose = true}) {
    commstyDialog(
        title: title,
        confirm: confirm,
        cancel: cancel,
        cancelTxt: cancelTxt,
        confirmTxt: confirmTxt,
        message: message,
        children: children,
        marginTop: marginTop,
        height: height,
        width: width,
        bgImg: bgImg,
        bgWhite: bgWhite,
        isShowClose: isShowClose);
  }

  ///普通 ，只有 confirm 与 close
  static commstyDialog(
      {required Function() confirm,
      Function()? cancel,
      String? confirmTxt,
      String? cancelTxt,
      message,
      title,
      bgWhite,
      height,
      width,
      bgImg,
      List<Widget>? children,
      marginTop,
      isShowClose = true}) {
    double dWidth = width ?? 310.w;
    Get.dialog(Stack(
      children: [
        Center(
          child: LFlexV([
            // LStack([
            //   LImage.easy(Assets.rzKkattentionPic, 146.w, 287.w),
            //   Positioned(right: 0, child: LImage.easy(Assets.rzCloseIconPop, 44.w, 44.w).paddingAll(12.w).onTapL(() => Get.back()))
            // ]),
            if (title != null)
              LText.easy(title, 20.sp, FontWeight.bold, const Color(0xFF015124))
                  .margin(top: 31.w),

            if (children != null) ...children,
            if (message != null)
              LText.easy(message, 16.sp, null, const Color(0xFF015124))
                  .margin(top: 30.w, bottom: 30.w)
                  .textAlign(TextAlign.center),
            // LExpand(),
            // LText(confirmTxt ?? S.current.confirm,
            //     lStyle: rzBtnSty
            //       ..fontSize = 16.sp
            //       ..width = 211.w
            //       ..height = 36.w,
            //     onTap: confirm),
              LRow.eazy([
                if (isShowClose)
                LText.easy(cancelTxt ?? '取消', 18.sp, fw7, AppColors.textColor)
                    .flex(1)
                    .size(null, 50.w)
                    .bgColor(const Color(0xFFEEEEEE))
                    .radius(25.w)
                    .center()
                    .onTapL(cancel ?? () => Get.back()),
                7.lsw,
                LText.easy(confirmTxt??'确定', 18.sp, fw7, Colors.white)
                    .gradient(const [
                      Color(0xFFFE3EC9),
                      Color(0xFFFB1D76),
                      Color(0xFFFFA253)
                    ], Alignment.centerRight)
                    .radius(25.w)
                    .center()
                    .flex(1)
                    .size(null, 50.w)
                    .onTapL(confirm)
              ]),
            25.lsh
          ])
              .paddingH(20.w)
              .radius(20.w)
              .gradient([Color(0xFFFEE3F3), Colors.white, Colors.white],
                  Alignment.bottomCenter)
              // .bgColor(0xFFE0FCDA.color)
              // .border(2.w, 0xFF2DDB92.color)
              .bgImg(bgImg)
              .size(dWidth, height),
        )
      ],
    ));
  }

  static LStyle get confrimSty => LStyle(alignment: Alignment.center, css: '''
                            width: 345px;
                            height: 45px;
                            background: #FA9A09;
                            border-radius: 5px;  
                            font-size: 18px;
                            font-weight: 600;
                            color: #FFFFFF;
                              ''');
}

DateTime? _lastWillPopAt;
Duration delay = const Duration(seconds: 2);

doubleExit({child}) {
  return WillPopScope(
    child: child,
    onWillPop: () async {
      print(_lastWillPopAt);
      if (_lastWillPopAt == null ||
          _lastWillPopAt != null &&
              DateTime.now().difference(_lastWillPopAt!) > delay) {
        _lastWillPopAt = DateTime.now();
        ToastUtils.toast("Press again to exit the app");
        return false;
      }
      return true;
    },
  );
}

class CommonControll extends GetxController {}

bool firstRequest = true;

Future<bool> checkInternetConnection({isNetwork = false}) async {
  // return true;
  var connectivityResult = await (Connectivity().checkConnectivity());
  if (connectivityResult == ConnectivityResult.mobile ||
      connectivityResult == ConnectivityResult.wifi) {
    return true;
  } else {
    if (firstRequest || isNetwork) {
      await Future.delayed(const Duration(seconds: 1));
      firstRequest = false;
      return await checkInternetConnection(isNetwork: isNetwork);
    }
    return false;
  }
}

bool isPermissionsDialog = false;

void showPermissionsDialog({title, message}) {
  Get.dialog(CupertinoAlertDialog(
    title: Text(title ?? "Unable to access network"),
    content: Column(
      children: [
        const SizedBox(height: 5),
        Text(message ?? "Allow the application to access the network"),
        const SizedBox(height: 12),
        Row(
          children: [
            LExpand(
              child: CupertinoDialogAction(
                onPressed: () async {
                  isPermissionsDialog = true;
                  Get.back();
                },
                child: const Text("关闭"),
              ),
            ),
            LExpand(
              child: CupertinoDialogAction(
                onPressed: () async {
                  isPermissionsDialog = true;
                  Get.back(result: await openAppSettings());
                },
                child: const Text("去设置"),
              ),
            ),
          ],
        )
      ],
    ),
  ));
  // showCupertinoDialog(
  //   context: context,
  //   builder: (BuildContext context) =>,
  // );
}
